
import advList from '$v/advList.ejs';
import { addAdvRequest, getAdvRequest } from '../api/adv';


const getNewAdvList = async (response) => {
    let getAdvResult = null
    try {
        getAdvResult = await getAdvRequest();
        console.log(getAdvResult);
    } catch (e) {
        alert('获取广告信息失败' + e.message);
    }

    response.render(advList({
        advList: getAdvResult
    }))
}


export default async (request, response) => {
    // 在页面渲染之间就要进行信息的获取
    await getNewAdvList(response)

    document.onclick = async function (e) {
        if (e.target.id === 'adv-save') {
            // 利用formData获取表单的各种信息
            const myformData = new FormData(document.advForm)
            console.log(myformData,'myformData');
            console.log(myformData.get('advTitle'),'advTiyle');
            console.log(myformData.get('advType'));
            console.log(myformData.get('advOrder'));

            try {
               await addAdvRequest(myformData)
                alert('广告信息添加成功')
                // 当广告信息添加成功之后进行页面的再次渲染 实现添加一次信息就及时显示包括已添加的全部广告信息
                // 思路：先封装一个函数 把
                document.getElementById('addClose').click()
                document.advForm.reset()
                getNewAdvList(response)
            } catch (e) {
                alert('广告信息添加出现异常' + e.message)
            }
        }
    }


    // 实现图片预览
    document.onchange = function (e) {

        if (e.target.id === 'advPic') {
            console.log(e.target.files[0]);
            const reader = new FileReader();
            reader.readAsDataURL(e.target.files[0]);

            reader.onload = function (e) {
                const preImg = document.getElementById('preImg')
                console.log(e.target.result,'e.target.result');
                preImg.src = e.target.result
                preImg.style.display = 'block'
            }
        }
    }
}